package com.example.petshopping.ui;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.chongwushangcheng.enums.ProductAuctionStatusEnum;
import com.example.chongwushangcheng.enums.ProductAuctionTypeEnum;
import com.example.chongwushangcheng.enums.ProductIsPromotedEnum;
import com.example.petshopping.R;
import com.example.petshopping.adapter.ProductAdapter;
import com.example.petshopping.model.AppPetAuctionItemRespVO;
import com.example.petshopping.model.CommonResult;
import com.example.petshopping.model.PageResult;
import com.example.petshopping.model.Product;
import com.example.petshopping.network.RetrofitClient;
import com.example.petshopping.ui.search.SearchActivity;
import com.google.android.flexbox.FlexboxLayout;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 专场对应的拍卖商品列表（专场详情页）
 */
public class SpecialPerformanceActivity extends AppCompatActivity {

    // 顶部与筛选控件
    private TextView btnBack;
    private LinearLayout searchPill;
    private TextView sortDefault;
    private LinearLayout sortPrice;
    private LinearLayout sortEndtime;
    private TextView caretPrice;
    private TextView caretEndtime;
    private TextView toggleFav;
    private FlexboxLayout tagsWrap;
    private TextView placeholder;
    private TextView title;

    // 排序与筛选状态
    private String activeKey = "default"; // default | price | endtime
    private final Map<String, String> sortState = new HashMap<>(); // price/endtime -> asc/desc
    private boolean favOnly = false;
    private final List<String> tags = new ArrayList<>();
    private final Set<String> selectedTags = new HashSet<>();

    // 专场id和标题
    String specialId;
    String specialTitle;

    // 商品列表与分页
    private RecyclerView productList;
    private final List<Product> products = new ArrayList<>();
    private int currentPage = 1;
    private boolean isLoading = false;
    private boolean hasMoreData = true;
    private static final int PAGE_SIZE = 10;
    private static final int REQUEST_CODE_AUCTION_DETAIL = 0x0A01;

    // 加载状态视图
    private View loadingMoreContainer;
    private View noMoreDataHint;
    private View loadFailedHint;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_special_performance);

        findViews(); // 初始化控件
        receiveExtras(); // 接收参数
        initData(); // 初始化数据
        initTopBar(); // 初始化顶部栏
        initSortBar(); // 初始化筛选栏
        initTags(); // 初始化标签
        setupScrollToLoadMore(); // 初始化滚动加载（监听）
        setupProductsList(); // 初始化商品列表
        loadProducts();// 加载商品
        updatePlaceholder(); // 更新占位提示
    }

    private void receiveExtras() {
        Intent intent = getIntent();
        if (intent == null) return;
        specialId = intent.getStringExtra("special_id");
        specialTitle = intent.getStringExtra("special_title");
        // 暂时将标题显示到占位提示中，后续可用于请求过滤或标题栏
        if (specialTitle != null) {
            title.setText(specialTitle);
        }
    }

    private void findViews() {
        title = findViewById(R.id.title);
        btnBack = findViewById(R.id.btn_back);
        searchPill = findViewById(R.id.search_pill);

        sortDefault = findViewById(R.id.sort_default);
        sortPrice = findViewById(R.id.sort_price);
        sortEndtime = findViewById(R.id.sort_endtime);
        caretPrice = findViewById(R.id.caret_price);
        caretEndtime = findViewById(R.id.caret_endtime);
        toggleFav = findViewById(R.id.toggle_fav);

        tagsWrap = findViewById(R.id.tags_wrap);
        placeholder = findViewById(R.id.placeholder);

        productList = findViewById(R.id.product_list);
        loadingMoreContainer = findViewById(R.id.loading_more_container);
        noMoreDataHint = findViewById(R.id.no_more_data_hint);
        loadFailedHint = findViewById(R.id.load_failed_hint);
    }

    private void initData() {
        sortState.put("price", "asc");
        sortState.put("endtime", "asc");

        // 标签初始化，首个为“全部(500)”
        tags.clear();
        tags.add("全部(500)");
        tags.add("热带鱼");
        tags.add("金鱼");
        tags.add("锦鲤");
        tags.add("龙鱼");
        tags.add("水草");
        tags.add("鱼缸");
        tags.add("过滤器");
        tags.add("饲料");
        tags.add("标签");
        tags.add("标签标签");
        tags.add("更多");
        tags.add("更多2");
        tags.add("更多3");
        tags.add("更多4");

        selectedTags.clear();
        selectedTags.add("全部(500)");
    }

    // 初始化顶部栏
    private void initTopBar() {
        btnBack.setOnClickListener(v -> finish());
        searchPill.setOnClickListener(v -> {
            Intent intent = new Intent(this, SearchActivity.class);
            startActivity(intent);
        });
    }

    // 初始化筛选栏
    private void initSortBar() {
        // 默认排序激活样式
        setActiveSort("default");

        sortDefault.setOnClickListener(v -> setActiveSort("default"));

        sortPrice.setOnClickListener(v -> {
            setActiveSort("price");
            toggleSortDirection("price");
            updateCaret(caretPrice, sortState.get("price"));
            ((TextView) sortPrice.findViewById(R.id.sort_price_text)).setTextColor(0xFF333333);
            caretPrice.setTextColor(0xFF8A5EEF);
            updatePlaceholder();
        });

        sortEndtime.setOnClickListener(v -> {
            setActiveSort("endtime");
            toggleSortDirection("endtime");
            updateCaret(caretEndtime, sortState.get("endtime"));
            ((TextView) sortEndtime.findViewById(R.id.sort_endtime_text)).setTextColor(0xFF333333);
            caretEndtime.setTextColor(0xFF8A5EEF);
            updatePlaceholder();
        });

        toggleFav.setOnClickListener(v -> {
            favOnly = !favOnly;
            toggleFav.setTextColor(favOnly ? 0xFF8A5EEF : 0xFF666666);
            updatePlaceholder();
        });
    }

    private void setActiveSort(String key) {
        activeKey = key;

        // 重置样式
        sortDefault.setTextColor(0xFF666666);
        sortDefault.setTypeface(null, Typeface.NORMAL);

        ((TextView) sortPrice.findViewById(R.id.sort_price_text)).setTextColor(0xFF666666);
        ((TextView) sortEndtime.findViewById(R.id.sort_endtime_text)).setTextColor(0xFF666666);

        // 重置箭头颜色
        updateCaret(caretPrice, sortState.get("price"));
        updateCaret(caretEndtime, sortState.get("endtime"));

        // 激活样式
        if ("default".equals(key)) {
            sortDefault.setTextColor(0xFF333333);
            sortDefault.setTypeface(null, Typeface.BOLD);
        } else if ("price".equals(key)) {
            ((TextView) sortPrice.findViewById(R.id.sort_price_text)).setTextColor(0xFF333333);
        } else if ("endtime".equals(key)) {
            ((TextView) sortEndtime.findViewById(R.id.sort_endtime_text)).setTextColor(0xFF333333);
        }
    }

    private void toggleSortDirection(String key) {
        String current = sortState.get(key);
        if (current == null) current = "asc";
        sortState.put(key, "asc".equals(current) ? "desc" : "asc");
    }

    private void updateCaret(TextView caretView, String direction) {
        if (caretView == null) return;
        boolean isAsc = "asc".equals(direction);
        caretView.setText(isAsc ? "▲" : "▼");
        // 非激活状态箭头保持默认灰；激活项在点击时会被再次调用
        caretView.setTextColor(0xFF999999);
    }

    // 初始化标签
    private void initTags() {
        tagsWrap.removeAllViews();

        for (int i = 0; i < tags.size(); i++) {
            final String label = tags.get(i);

            TextView tagView = new TextView(this);
            tagView.setText(label);
            tagView.setTextSize(13);
            tagView.setPadding(dp(12), dp(6), dp(12), dp(6));
            tagView.setTextColor(0xFF333333);
            tagView.setBackgroundResource(R.drawable.bg_tag_normal);

            FlexboxLayout.LayoutParams lp = new FlexboxLayout.LayoutParams(
                    FlexboxLayout.LayoutParams.WRAP_CONTENT,
                    FlexboxLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(dp(5), dp(5), dp(5), dp(5));
            tagView.setLayoutParams(lp);

            if (i == 0) {
                // “全部”样式
                tagView.setBackgroundResource(R.drawable.bg_tag_all);
                tagView.setTextColor(0xFF8A5EEF);
            }

            tagView.setOnClickListener(v -> onTagClicked(label));

            tagsWrap.addView(tagView);
        }

        refreshTagsSelection();
    }

    // 标签点击处理
    private void onTagClicked(String label) {
        String allLabel = tags.get(0);
        if (label.equals(allLabel)) {
            selectedTags.clear();
            selectedTags.add(allLabel);
        } else {
            if (selectedTags.contains(allLabel)) {
                selectedTags.remove(allLabel);
            }
            if (selectedTags.contains(label)) {
                selectedTags.remove(label);
            } else {
                selectedTags.add(label);
            }
            if (selectedTags.isEmpty()) {
                selectedTags.add(allLabel);
            }
        }
        refreshTagsSelection();
        updatePlaceholder();
    }

    // 刷新标签选中样式
    private void refreshTagsSelection() {
        String allLabel = tags.get(0);
        for (int i = 0; i < tagsWrap.getChildCount(); i++) {
            View child = tagsWrap.getChildAt(i);
            if (!(child instanceof TextView)) continue;
            TextView tv = (TextView) child;
            String label = tv.getText().toString();

            boolean selected = selectedTags.contains(label);
            boolean isAll = label.equals(allLabel);

            if (isAll) {
                tv.setBackgroundResource(selected ? R.drawable.bg_tag_all_selected : R.drawable.bg_tag_all);
                tv.setTextColor(selected ? 0xFF8A5EEF : 0xFF8A5EEF);
            } else {
                tv.setBackgroundResource(selected ? R.drawable.bg_tag_selected : R.drawable.bg_tag_normal);
                tv.setTextColor(selected ? 0xFF8A5EEF : 0xFF333333);
            }
        }
    }

    // 配置滚动加载更多
    private void setupScrollToLoadMore() {
        NestedScrollView scrollView = findViewById(R.id.nested_scroll_view);
        if (scrollView != null) {
            scrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
                if (!isLoading && hasMoreData && scrollY > oldScrollY) {
                    if (scrollY + v.getHeight() >= v.getChildAt(0).getMeasuredHeight() - 100) {
                        loadMoreProducts();
                    }
                }
            });
        }
    }

    // 配置商品列表
    private void setupProductsList() {
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        productList.setLayoutManager(layoutManager);

        ProductAdapter adapter = new ProductAdapter(this, products, R.layout.item_product_list);
        productList.setAdapter(adapter);

        adapter.setOnProductClickListener(new ProductAdapter.OnProductClickListener() {
            @Override
            public void onProductClick(Product product, int position) {
                Intent intent = new Intent(SpecialPerformanceActivity.this, com.example.chongwushangcheng.activity.AquariumDetailActivity.class);
                intent.putExtra("id", product.getId());
                intent.putExtra("spuId", product.getSpuId());
                intent.putExtra("name", product.getName());
                intent.putExtra("price", product.getPrice());
                intent.putExtra("sellerId", product.getSellerId());
                intent.putExtra("sellerName", product.getSellerName());
                intent.putExtra("sellerAvatar", product.getSellerAvatar());
                intent.putExtra("auctionEndTime", product.getAuctionEndTime());
                overridePendingTransition(0, 0);
                startActivityForResult(intent, REQUEST_CODE_AUCTION_DETAIL);
            }

            @Override
            public void onDeleteClick(Product product, int position) {
                products.remove(position);
                adapter.notifyItemRemoved(position);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_AUCTION_DETAIL && resultCode == RESULT_OK) {
            // 当从详情页返回且返回RESULT_OK，重新加载专场商品数据
            loadProducts();
        }
    }

    // 加载商品
    private void loadProducts() {
        currentPage = 1;
        isLoading = true;
        hasMoreData = true;

        hideLoadingMore();
        hideNoMoreDataHint();
        hideLoadFailedHint();

        Call<CommonResult<PageResult<AppPetAuctionItemRespVO>>> call = RetrofitClient.getInstance()
                .getApiService()
                .getPetAuctionItemPage(
                        currentPage,
                        PAGE_SIZE,
                        null,
                        null, // 拍卖类型（英式拍卖）
                        null,
                        null,
                        ProductAuctionStatusEnum.STARTING.getStatus(), // 拍卖状态（进行中）
                        null, // 精品推荐(拍卖这里无论是否精品都展示)
                        null,
                        null,
                        Integer.valueOf(specialId) // 专场ID
                );

        call.enqueue(new Callback<CommonResult<PageResult<AppPetAuctionItemRespVO>>>() {
            @Override
            public void onResponse(Call<CommonResult<PageResult<AppPetAuctionItemRespVO>>> call,
                                   Response<CommonResult<PageResult<AppPetAuctionItemRespVO>>> response) {
                try {
                    if (response.isSuccessful() && response.body() != null) {
                        CommonResult<PageResult<AppPetAuctionItemRespVO>> result = response.body();
                        if (result.isSuccess() && result.getData() != null) {
                            List<AppPetAuctionItemRespVO> auctionItems = result.getData().getList();
                            if (auctionItems != null && !auctionItems.isEmpty()) {
                                convertAndLoadProducts(auctionItems, true);

                                PageResult<AppPetAuctionItemRespVO> pageResult = result.getData();
                                hasMoreData = auctionItems.size() >= PAGE_SIZE &&
                                        (pageResult.getTotal() == null || products.size() < pageResult.getTotal());

                                hideLoadFailedHint();
                            } else {
                                showLoadFailedHint();
                                hasMoreData = false;
                            }
                        } else {
                            showLoadFailedHint();
                            hasMoreData = false;
                        }
                    } else {
                        showLoadFailedHint();
                        hasMoreData = false;
                    }
                } catch (Exception e) {
                    showLoadFailedHint();
                    hasMoreData = false;
                } finally {
                    isLoading = false;
                }
            }

            @Override
            public void onFailure(Call<CommonResult<PageResult<AppPetAuctionItemRespVO>>> call, Throwable t) {
                showLoadFailedHint();
                hasMoreData = false;
                isLoading = false;
            }
        });
    }

    // 加载更多商品
    private void loadMoreProducts() {
        if (isLoading || !hasMoreData) {
            return;
        }

        isLoading = true;
        currentPage++;
        showLoadingMore();

        Call<CommonResult<PageResult<AppPetAuctionItemRespVO>>> call = RetrofitClient.getInstance()
                .getApiService()
                .getPetAuctionItemPage(
                        currentPage,
                        PAGE_SIZE,
                        null,
                        null, // 拍卖类型（英式拍卖）
                        null,
                        null,
                        ProductAuctionStatusEnum.STARTING.getStatus(), // 拍卖状态（进行中）
                        null, // 精品推荐(拍卖这里无论是否精品都展示)
                        null,
                        null,
                        Integer.valueOf(specialId) // 专场ID
                );

        call.enqueue(new Callback<CommonResult<PageResult<AppPetAuctionItemRespVO>>>() {
            @Override
            public void onResponse(Call<CommonResult<PageResult<AppPetAuctionItemRespVO>>> call,
                                   Response<CommonResult<PageResult<AppPetAuctionItemRespVO>>> response) {
                try {
                    if (response.isSuccessful() && response.body() != null) {
                        CommonResult<PageResult<AppPetAuctionItemRespVO>> result = response.body();
                        if (result.isSuccess() && result.getData() != null) {
                            List<AppPetAuctionItemRespVO> auctionItems = result.getData().getList();
                            if (auctionItems != null && !auctionItems.isEmpty()) {
                                convertAndLoadProducts(auctionItems, false);

                                PageResult<AppPetAuctionItemRespVO> pageResult = result.getData();
                                hasMoreData = auctionItems.size() >= PAGE_SIZE &&
                                        (pageResult.getTotal() == null || products.size() < pageResult.getTotal());

                                hideLoadFailedHint();
                                if (!hasMoreData) {
                                    showNoMoreDataHint();
                                }
                            } else {
                                hasMoreData = false;
                                showNoMoreDataHint();
                            }
                        } else {
                            currentPage--; // 回退页码
                            showLoadFailedHint();
                        }
                    } else {
                        currentPage--; // 回退页码
                        showLoadFailedHint();
                    }
                } catch (Exception e) {
                    currentPage--; // 回退页码
                    showLoadFailedHint();
                } finally {
                    isLoading = false;
                    hideLoadingMore();
                }
            }

            @Override
            public void onFailure(Call<CommonResult<PageResult<AppPetAuctionItemRespVO>>> call, Throwable t) {
                currentPage--; // 回退页码
                isLoading = false;
                hideLoadingMore();
                showLoadFailedHint();
            }
        });
    }

    // 显示加载更多
    private void convertAndLoadProducts(List<AppPetAuctionItemRespVO> auctionItems, boolean clearExisting) {
        int startPosition = products.size();

        if (clearExisting) {
            products.clear();
            startPosition = 0;
        }

        for (AppPetAuctionItemRespVO item : auctionItems) {
            Product product = new Product(
                    item.getId(),
                    item.getSpuId(),
                    item.getName(),
                    item.getPicUrl(),
                    "¥" + item.getCurrentPrice(),
                    item.getSellerId(),
                    item.getSellerName() != null ? item.getSellerName() : "未知卖家",
                    item.getSellerAvatar(),
                    formatEndTime(item.getEndTime())
            );

            if (item.getIsPromoted() != null && item.getIsPromoted()) {
                product.setPromoted(true);
            }

            products.add(product);
        }

        if (productList.getAdapter() != null) {
            if (clearExisting) {
                productList.getAdapter().notifyDataSetChanged();
            } else {
                productList.getAdapter().notifyItemRangeInserted(startPosition, auctionItems.size());
            }
        }
    }

    // 格式化时间
    private String formatEndTime(LocalDateTime endTime) {
        if (endTime == null) {
            return "时间未定";
        }
        try {
            // 获取当前时间（加上8小时时区偏移）
            LocalDateTime now = LocalDateTime.now().plusHours(8);
            // 计算实际结束时间
            LocalDateTime actualEndTime = endTime.plusHours(8);

            // 如果当前时间已经超过了结束时间，返回"已截拍"
            if (now.isAfter(actualEndTime)) {
                return "已截拍";
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd HH:mm 截拍");
            return actualEndTime.format(formatter);
        } catch (Exception e) {
            return "时间格式错误";
        }
    }

    // 显示加载更多
    private void showLoadingMore() {
        if (loadingMoreContainer != null) {
            loadingMoreContainer.setVisibility(View.VISIBLE);
        }
        if (noMoreDataHint != null) {
            noMoreDataHint.setVisibility(View.GONE);
        }
    }

    // 隐藏加载更多
    private void hideLoadingMore() {
        if (loadingMoreContainer != null) {
            loadingMoreContainer.setVisibility(View.GONE);
        }
    }

    // 显示没有更多数据
    private void showNoMoreDataHint() {
        if (noMoreDataHint != null) {
            noMoreDataHint.setVisibility(View.VISIBLE);
        }
        if (loadingMoreContainer != null) {
            loadingMoreContainer.setVisibility(View.GONE);
        }
        if (loadFailedHint != null) {
            loadFailedHint.setVisibility(View.GONE);
        }
    }

    // 隐藏没有更多数据
    private void hideNoMoreDataHint() {
        if (noMoreDataHint != null) {
            noMoreDataHint.setVisibility(View.GONE);
        }
    }

    // 显示加载失败
    private void showLoadFailedHint() {
        if (loadFailedHint != null) {
            loadFailedHint.setVisibility(View.VISIBLE);
        }
        if (loadingMoreContainer != null) {
            loadingMoreContainer.setVisibility(View.GONE);
        }
        if (noMoreDataHint != null) {
            noMoreDataHint.setVisibility(View.GONE);
        }
    }

    // 隐藏加载失败
    private void hideLoadFailedHint() {
        if (loadFailedHint != null) {
            loadFailedHint.setVisibility(View.GONE);
        }
    }

    // 更新占位符
    private void updatePlaceholder() {
        String sortText;
        if ("default".equals(activeKey)) {
            sortText = "默认排序";
        } else if ("price".equals(activeKey)) {
            sortText = "价格 (" + ("asc".equals(sortState.get("price")) ? "升序" : "降序") + ")";
        } else {
            sortText = "结标时间 (" + ("asc".equals(sortState.get("endtime")) ? "升序" : "降序") + ")";
        }

        String favText = favOnly ? " · 仅看关注" : "";
        String text = "当前排序：" + sortText + favText + "；可继续选择标签。";
        placeholder.setText(text);
    }

    // 获取dp值
    private int dp(int value) {
        float density = getResources().getDisplayMetrics().density;
        return (int) (value * density + 0.5f);
    }
}

